package com.ipzoe.web.controller.mem;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import java.util.List;
import java.util.Arrays;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ipzoe.common.utils.SecurityUtils;
import com.ipzoe.common.utils.StringUtils;
import com.ipzoe.mem.domain.MemberSobotRecord;
import com.ipzoe.mem.service.IMemberSobotRecordService;
import com.ipzoe.system.service.IRegionService;
import com.ipzoe.system.service.ISysDictDataService;
import com.ipzoe.web.convert.MemberConvert;
import com.ipzoe.web.model.mem.MemberExcelVO;
import com.ipzoe.web.model.mem.MemberListQueryDTO;
import com.ipzoe.web.model.mem.MemberListVO;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ipzoe.common.annotation.Log;
import com.ipzoe.common.core.controller.BaseController;
import com.ipzoe.common.core.domain.AjaxResult;
import com.ipzoe.common.enums.BusinessType;
import com.ipzoe.mem.domain.Member;
import com.ipzoe.mem.service.IMemberService;
import com.ipzoe.common.utils.poi.ExcelUtil;
import com.ipzoe.common.core.page.TableDataInfo;

/**
 * 会员Controller
 *
 * @author eric
 * @date 2020-08-20
 */
@RestController
@RequestMapping("/member/member")
public class MemberController extends BaseController {

    @Autowired
    private IMemberService iMemberService;
    @Autowired
    private ISysDictDataService iSysDictDataService;
    @Autowired
    private IRegionService regionService;
    @Autowired
    private IMemberSobotRecordService memberSobotRecordService;

    /**
     * 查询会员列表
     */
    @PreAuthorize("@ss.hasPermi('member:member:list')")
    @GetMapping("/list")
    public TableDataInfo list(MemberListQueryDTO memberListQueryDTO) {
        startPage();
        LambdaQueryWrapper<Member> lqw = new LambdaQueryWrapper<Member>();
        if (StringUtils.isNotBlank(memberListQueryDTO.getNickname())) {
            lqw.like(Member::getNickname, memberListQueryDTO.getNickname());
        }
        if (memberListQueryDTO.getMemberLevel() != null) {
            lqw.eq(Member::getMemberLevel, memberListQueryDTO.getMemberLevel());
        }
        lqw.apply(StrUtil.isNotEmpty(memberListQueryDTO.getLastLoginBeginTime()),"date_format(last_login_time,'%y%m%d') >= date_format({0},'%y%m%d')",memberListQueryDTO.getLastLoginBeginTime());
        lqw.apply(StrUtil.isNotEmpty(memberListQueryDTO.getLastLoginEndTime()),"date_format(last_login_time,'%y%m%d') <= date_format({0},'%y%m%d')",memberListQueryDTO.getLastLoginEndTime());
        lqw.apply(StrUtil.isNotEmpty(memberListQueryDTO.getRegisterBeginTime()),"date_format(register_time,'%y%m%d') >= date_format({0},'%y%m%d')",memberListQueryDTO.getRegisterBeginTime());
        lqw.apply(StrUtil.isNotEmpty(memberListQueryDTO.getRegisterEndTime()),"date_format(register_time,'%y%m%d') <= date_format({0},'%y%m%d')",memberListQueryDTO.getRegisterEndTime());
        if (memberListQueryDTO.getSex() != null) {
            lqw.eq(Member::getSex, memberListQueryDTO.getSex());
        }
        if (memberListQueryDTO.getDiveLevel() != null) {
            lqw.eq(Member::getDiveLevel, memberListQueryDTO.getDiveLevel());
        }
        if(memberListQueryDTO.getCountryId() != null){
            lqw.eq(Member::getCountryId, memberListQueryDTO.getCountryId());
        }
        List<Member> list = iMemberService.list(lqw);
        List<MemberListVO> result = MemberConvert.INSTANCE.convertList(list);
        if(CollUtil.isNotEmpty(result)){
            result.forEach(t->{
                if(t.getCountryId() != null){
                    t.setCountry(regionService.getById(t.getCountryId()));
                }
            });
        }
        return getDataTable(result);
    }

    @GetMapping("/sobotRecord/list")
    public TableDataInfo sobotRecord(Long id){
        startPage();
        LambdaQueryWrapper<MemberSobotRecord> lqw = new QueryWrapper<MemberSobotRecord>().lambda()
                .eq(MemberSobotRecord::getMemberId, id)
                .orderByDesc(MemberSobotRecord::getStartTime);
        List<MemberSobotRecord> list = memberSobotRecordService.list(lqw);
        return getDataTable(list);
    }

    /**
     * 导出会员列表
     */
    @PreAuthorize("@ss.hasPermi('member:member:export')")
    @Log(title = "会员", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public AjaxResult export(MemberListQueryDTO memberListQueryDTO) {
        LambdaQueryWrapper<Member> lqw = new LambdaQueryWrapper<Member>();
        if (StringUtils.isNotBlank(memberListQueryDTO.getNickname())) {
            lqw.like(Member::getNickname, memberListQueryDTO.getNickname());
        }
        if (memberListQueryDTO.getMemberLevel() != null) {
            lqw.eq(Member::getMemberLevel, memberListQueryDTO.getMemberLevel());
        }
        lqw.apply(StrUtil.isNotEmpty(memberListQueryDTO.getLastLoginBeginTime()),"date_format(last_login_time,'%y%m%d') >= date_format({0},'%y%m%d')",memberListQueryDTO.getLastLoginBeginTime());
        lqw.apply(StrUtil.isNotEmpty(memberListQueryDTO.getLastLoginEndTime()),"date_format(last_login_time,'%y%m%d') <= date_format({0},'%y%m%d')",memberListQueryDTO.getLastLoginEndTime());
        lqw.apply(StrUtil.isNotEmpty(memberListQueryDTO.getRegisterBeginTime()),"date_format(register_time,'%y%m%d') >= date_format({0},'%y%m%d')",memberListQueryDTO.getRegisterBeginTime());
        lqw.apply(StrUtil.isNotEmpty(memberListQueryDTO.getRegisterEndTime()),"date_format(register_time,'%y%m%d') <= date_format({0},'%y%m%d')",memberListQueryDTO.getRegisterEndTime());
        if (memberListQueryDTO.getSex() != null) {
            lqw.eq(Member::getSex, memberListQueryDTO.getSex());
        }
        if (memberListQueryDTO.getDiveLevel() != null) {
            lqw.eq(Member::getDiveLevel, memberListQueryDTO.getDiveLevel());
        }
        List<Member> list = iMemberService.list(lqw);
        List<MemberExcelVO> excelVOList = MemberConvert.INSTANCE.convert(list);
        excelVOList.forEach(m -> {
            if (ObjectUtil.isNotNull(m.getDiveLevel())) {
                m.setDiveLevelStr(iSysDictDataService.selectDictLabel("mem_member_dan_level", String.valueOf(m.getDiveLevel())));
            }
            if (ObjectUtil.isNotNull(m.getIndustryId())) {
                m.setIndustryStr(String.valueOf(m.getIndustryId()));
            }
            if (ObjectUtil.isNotNull(m.getMemberLevel())) {
                m.setMemberLevelStr(iSysDictDataService.selectDictLabel("mem_member_level", String.valueOf(m.getMemberLevel())));
            }
            if (ObjectUtil.isNotNull(m.getMemberStatus())) {
                m.setMemberStatusStr(iSysDictDataService.selectDictLabel("mem_member_status", String.valueOf(m.getMemberStatus())));
            }
            if (ObjectUtil.isNotNull(m.getSex())) {
                m.setSexStr(iSysDictDataService.selectDictLabel("sys_user_sex", String.valueOf(m.getSex())));
            }
            if(ObjectUtil.isNotNull(m.getStatus())){
                m.setStatusStr(iSysDictDataService.selectDictLabel("mem_account_status", String.valueOf(m.getStatus())));
            }

        });


        ExcelUtil<MemberExcelVO> util = new ExcelUtil<MemberExcelVO>(MemberExcelVO.class);
        return util.exportExcel(excelVOList, "member");
    }

    /**
     * 获取会员详细信息
     */
    @PreAuthorize("@ss.hasPermi('member:member:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(iMemberService.getById(id));
    }

    /**
     * 新增会员
     */
    @PreAuthorize("@ss.hasPermi('member:member:add')")
    @Log(title = "会员", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Member member) {
        return toAjax(iMemberService.save(member) ? 1 : 0);
    }

    /**
     * 修改会员
     */
    @PreAuthorize("@ss.hasPermi('member:member:edit')")
    @Log(title = "会员", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Member member) {
        return toAjax(iMemberService.updateById(member) ? 1 : 0);
    }

    /**
     * 删除会员
     */
    @PreAuthorize("@ss.hasPermi('member:member:remove')")
    @Log(title = "会员", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(iMemberService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /**
     * 冻结用户
     */
    @PreAuthorize("@ss.hasPermi('member:member:frozen')")
    @Log(title = "会员冻结", businessType = BusinessType.UPDATE)
    @PutMapping("/frozen/{id}")
    public AjaxResult frozen(@PathVariable Long id) {
        Member member = new Member();
        member.setId(id).setStatus(2).setUpdateBy(SecurityUtils.getUsername());
        iMemberService.updateById(member);
        return toAjax(1);
    }

    /**
     * 解冻用户
     */
    @PreAuthorize("@ss.hasPermi('member:member:thaw')")
    @Log(title = "会员解冻", businessType = BusinessType.UPDATE)
    @PutMapping("/thaw/{id}")
    public AjaxResult thaw(@PathVariable Long id) {
        Member member = new Member();
        member.setId(id).setStatus(1).setUpdateBy(SecurityUtils.getUsername());
        iMemberService.updateById(member);
        return toAjax(1);
    }


}
